//
//  PhotoBrowserCell.swift
//  LVWeibo
//
//  Created by lv on 15/7/5.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit
import SDWebImage
import FFAutoLayout

protocol PhotoBrowserCellDelegate: NSObjectProtocol {
    func photoViewerCellDidTapImage()
}

class PhotoBrowserCell: UICollectionViewCell,UIScrollViewDelegate {
    
    // 代理属性
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    var imageURL : NSURL? {
        didSet {
            // 重新设置ScrollView
            resetScrollView()
            // 菊花开始加载
            indicator.startAnimating()
            imageView.sd_setImageWithURL(imageURL, placeholderImage: nil) { (image, error, _, _) -> Void in
                // 设置图片的frame
                self.imageView.frame = CGRect(origin: CGPointZero, size:
                    self.displayImageSize(image))
                // 设置图片显示位置
                self.calcImagePosition(image)
                
                // 图片加载完成结束动画
                self.indicator.stopAnimating()
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 添加子控件
        prepareScrollView()
        
        addSubview(indicator)
        indicator.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: nil)
        
        // 添加imageView的手势监听
        let tap = UITapGestureRecognizer(target: self, action: "clickImage")
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
    }
    
    // MARK:- clickImage
    func clickImage () {
        photoDelegate?.photoViewerCellDidTapImage()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK:- 准备scrollView
    private func prepareScrollView() {
        scrollView.frame = bounds
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        addSubview(scrollView)
        scrollView.addSubview(imageView)
    }
    
    //MARK:- 重新设置ScrollView
    private func resetScrollView() {
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    // 缩放处理
    //MARK:- 实现ScrollView的代理方法
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    // 缩放结束后执行，调整图片边距
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        if offsetX < 0 {
            offsetX = 0
        }
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        if offsetY < 0 {
            offsetY = 0
        }
        // 设置边距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    
    //MARK:- 根据图像计算显示尺寸(等比例缩放)
    private func displayImageSize(image: UIImage) ->CGSize {
        let scale = image.size.height / image.size.width
        let h = bounds.width * scale
        return CGSize(width: bounds.width, height: h)
    }
    
    //MARK:- 计算图片位置
    private func calcImagePosition(image: UIImage) {
        
        let size = displayImageSize(image)
        imageView.frame = CGRect(origin: CGPointZero, size: size)
        // 长图
        if size.height > bounds.height {
            scrollView.contentInset = UIEdgeInsetsZero
            scrollView.contentSize = size
        }else {
            // 短图
            let top = (bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
        }
    }
    
    
    /// 懒加载子控件
    lazy private var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    lazy private var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}
